package thread.demo05_2.ReentrantReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读读共享
 * 
 * @author mengzhang6
 *
 */
public class ReentrantReadWriteLockDemo {
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	public static void main(String[] args) {

		ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();

		new Thread(() -> demo.read(), "ThreadA").start();
		new Thread(() -> demo.read(), "ThreadB").start();
		/**
		 * 从结果可以看出两个线程之间，获取锁的时间几乎同时，说明lock.readLock().lock();
		 * 允许多个线程同时执行lock（）方法后面的代码。
		 */
	}

	private void read() {
		try {
			try {
				lock.readLock().lock();
				System.out.println("获得读锁" + Thread.currentThread().getName() + " 时间:" + System.currentTimeMillis());
				// 模拟读操作时间为5秒
				Thread.sleep(5000);
			} finally {
				lock.readLock().unlock();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
